package com.jy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jy.common.enums.ResponseWrapper;
import com.jy.common.model.user.param.AddAddressParam;
import com.jy.common.model.user.param.DeleteAddressChildParam;
import com.jy.common.model.user.param.DeleteAddressParam;
import com.jy.entity.Address;
import com.jy.mapper.AddressMapper;
import com.jy.mapper.UserMapper;
import com.jy.service.AddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 用户的地址表 服务实现类
 * </p>
 *
 * @author fzg
 * @since 2025-01-16
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

    private final AddressMapper addressMapper;

    public AddressServiceImpl(AddressMapper addressMapper, UserMapper userMapper) {
        this.addressMapper = addressMapper;
    }

    @Override
    public ResponseWrapper getAddressList(Integer userAidByToken) {

        List<Address> addresses = addressMapper.selectList(new LambdaQueryWrapper<Address>()
                .eq(Address::getUserAid, userAidByToken)
                .orderByDesc(Address::getUpdateTime)
        );

        // 排序：默认地址第一个
        Address defaultAddress = null;
        for (Address address : addresses) {
            if (address.getIsDefault()) {
                defaultAddress = address;
                break;
            }
        }
        if (defaultAddress!= null) {
            addresses.remove(defaultAddress);
            addresses.add(0, defaultAddress);
        }

        ArrayList<HashMap<String, Object>> hashMaps = new ArrayList<>();
        for (Address address : addresses) {
            HashMap<String, Object> map = getStringObjectHashMap(address);
            hashMaps.add(map);
        }
        return ResponseWrapper.markSuccess(hashMaps);
    }

    private HashMap<String, Object> getStringObjectHashMap(Address address) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("addressAid", address.getAid());
        map.put("isSelected",false);
        map.put("isDefault", address.getIsDefault());
        map.put("addressee", address.getReceiverName());
        map.put("phone", "+86 " + address.getReceiverPhone());
        map.put("province",checkEmptyStr(address.getProvince()));
        map.put("city",checkEmptyStr(address.getCity()));
        map.put("county",checkEmptyStr(address.getCounty()));
        map.put("detailAddress",checkEmptyStr(address.getDetailAddress()));
        return map;
    }

    @Override
    public ResponseWrapper addAddress(Integer userAidByToken, AddAddressParam param) {

        String completeAddress;
        String province;
        String city;
        String county;
        String location = param.getLocation();
        if(location.contains("/")){
            String[] split = location.split("/");
            completeAddress = split[0] + split[1] + split[2];
            province = split[0];
            city = split[1];
            county = split[2];
        }else {
            completeAddress = location;
            province = location;
            city = location;
            county = location;
        }
        // 如果为默认地址（param.getIsDefault = true）那么就要修改我的其他地址让其他地址都不是默认地址
        if (param.getIsDefault()){
            List<Address> addresses = addressMapper.selectList(new LambdaQueryWrapper<Address>()
                    .eq(Address::getUserAid, userAidByToken)
            );
            for (Address address : addresses) {
                address.setIsDefault(false);
                addressMapper.updateById(address);
            }
        }

        if (param.getAddressAid() > 0){
            // 更新地址
            Address address = addressMapper.selectById(param.getAddressAid());
            address.setReceiverName(param.getName());
            address.setReceiverPhone(param.getPhone());
            address.setCompleteAddress(completeAddress);
            address.setDetailAddress(param.getDetailAdress());
            address.setIsDefault(param.getIsDefault());
            address.setProvince(province);
            address.setCity(city);
            address.setCounty(county);
            int updateById = addressMapper.updateById(address);
            if (updateById > 0){
                return ResponseWrapper.markCustomSuccess("更新成功");
            }else {
                return ResponseWrapper.markCustomError("更新失败，请稍后再试...");
            }
        }else {
            int insert = addressMapper.insert(new Address() {{
                setUserAid(userAidByToken.longValue());
                setCompleteAddress(completeAddress);
                setIsDefault(param.getIsDefault());
                setProvince(province);
                setCity(city);
                setCounty(county);
                setDetailAddress(param.getDetailAdress());
                setReceiverName(param.getName());
                setReceiverPhone(param.getPhone());
            }});
            if (insert > 0){
                return ResponseWrapper.markCustomSuccess("添加成功");
            }else {
                return ResponseWrapper.markCustomError("添加失败，请稍后再试...");
            }
        }


    }

    @Override
    public ResponseWrapper deleteAddress(DeleteAddressParam param) {
        List<DeleteAddressChildParam> addressArray = param.getAddressArray();
        if (param.getIsAllSelect()){
            // 全选，全删
            for (DeleteAddressChildParam deleteAddressChildParam : addressArray) {
                Integer addressAid = deleteAddressChildParam.getAddressAid();
                addressMapper.deleteById(addressAid);
            }
        }else {
            for (DeleteAddressChildParam deleteAddressChildParam : addressArray) {
                if (deleteAddressChildParam.getIsSelected()){
                    Integer addressAid = deleteAddressChildParam.getAddressAid();
                    addressMapper.deleteById(addressAid);
                }
            }
        }
        return ResponseWrapper.markSuccess();
    }

    @Override
    public ResponseWrapper getAddressInfoByAid(Integer addressAid) {
        HashMap<String, Object> result = new HashMap<>();
        Address address = addressMapper.selectById(addressAid);
        HashMap<String, Object> customFormData = new HashMap<>();
        customFormData.put("name",address.getReceiverName());
        customFormData.put("phone",address.getReceiverPhone());
        // location包含“/”
        String location = address.getProvince() + "/" + address.getCity() + "/" + address.getCounty();
        customFormData.put("location",location);
        customFormData.put("detailAdress",address.getDetailAddress());
        result.put("customFormData",customFormData);
        result.put("isDefaultAddress",address.getIsDefault());
        return ResponseWrapper.markSuccess(result);
    }

    private String checkEmptyStr(String str){
        return (str==null || str.equals("")) ? "" : str;
    }


}
